package com.yoda.common.validator;

import com.yoda.common.validator.annotations.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 列表值约束验证器
 *
 * @author lenovo
 * @date 2022/12/14
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {

    private Set<Integer> set = new HashSet<>();
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] values = constraintAnnotation.values();
        if (!Objects.isNull(values)&&values.length!=0){
            set.addAll(new ArrayList<>(Arrays.stream(values).boxed().collect(Collectors.toList())));
        }
    }

    /**
     * 是否有效
     *
     * @param value                      提交的值
     * @param constraintValidatorContext 约束验证器上下文
     * @return boolean
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        return set.contains(value);
    }
}